cmake_minimum_required(VERSION 2.8.8)

include_directories(@CONF_INCLUDE_DIR@)

include(CMakeParseArguments)

FILE(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/bundles)

# add_bundle(<name>    # Bundle name (e.g. fr.osgi.deployment)
#   VERSION version         # Bundle version (3 numbers, dot-separated, e.g. 1.2.10)
#   SOURCES files...        # Bundle source files.
# )
#
# <name>.properties and <name>.extensions.xml, if found, are automatically handled.
#
function(add_bundle BUNDLE_NAME)

    set(Arguments VERSION)
    set(MultiArguments SOURCES)
    cmake_parse_arguments(BUNDLE "" "${Arguments}" "${MultiArguments}" ${ARGN})

    set(LIBRARY     ${BUNDLE_NAME})
    set(BUNDLE      ${BUNDLE_NAME}_${BUNDLE_VERSION}.bndl)
    set(BUNDLESPEC  ${BUNDLE_NAME}.bundlespec)

    if(NOT TARGET ${LIBRARY})
        add_library(${LIBRARY} MODULE EXCLUDE_FROM_ALL ${BUNDLE_SOURCES})
        set_target_properties(${LIBRARY} PROPERTIES PREFIX "")
        if(${CMAKE_COMPILER_IS_GNUCXX})
            set_target_properties(${LIBRARY} PROPERTIES COMPILE_FLAGS "-std=c++11")
        endif()
        target_link_libraries(${LIBRARY} OSGi++)
    endif()

    # Automatically adds properties file, if found.
    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}.properties)
        set(OTHER_FILES -f${BUNDLE_NAME}.properties=${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}.properties)
    endif()
    # Automatically adds extension file, if found.
    if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}.extensions.xml)
        set(OTHER_FILES ${OTHER_FILES} -fextensions.xml=${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLE_NAME}.extensions.xml)
    endif()

    configure_file(${CMAKE_CURRENT_SOURCE_DIR}/${BUNDLESPEC}.in ${CMAKE_CURRENT_BINARY_DIR}/${BUNDLESPEC})

    add_custom_command(OUTPUT ${PROJECT_BINARY_DIR}/bundles/${BUNDLE}
        COMMENT Packaging ${BUNDLE}
        COMMAND ${OSGi_PACKAGER}
                -I${CMAKE_CURRENT_BINARY_DIR}               # Uses configured files first.
                -I${CMAKE_CURRENT_SOURCE_DIR}
                -o ${PROJECT_BINARY_DIR}/bundles/${BUNDLE}
                ${OTHER_FILES}
                ${CMAKE_CURRENT_BINARY_DIR}/${BUNDLESPEC}   # Bundlespec file is the last argument.
        DEPENDS ${LIBRARY}
                ${CMAKE_CURRENT_BINARY_DIR}/${BUNDLESPEC}
    )

    add_custom_target(${BUNDLE} ALL DEPENDS ${PROJECT_BINARY_DIR}/bundles/${BUNDLE})

endfunction()
